package main

import (
	"fmt"
	"github.com/julienschmidt/httprouter"
	"log"
	"net/http"
)

const AddForm = `<html>
<form method="POST" action="/add">
URL: <input type="text" name="url">
<input type="submit" value="Add">
</form>
</html>
`

var store = NewUrlStore("store.json")

func Redirect(w http.ResponseWriter, req *http.Request) {
	key := req.URL.Path[1:]
	url := store.Get(key)
	if url == "" {
		http.NotFound(w, req)
		return
	}
	http.Redirect(w, req, url, http.StatusFound)
}

func Add(w http.ResponseWriter, req *http.Request) {
	url := req.FormValue("url")
	if url == "" {
		fmt.Fprintf(w, AddForm)
		return
	}
	key := store.Put(url)
	fmt.Fprintf(w, "http://localhost:8080/%s", key)
}

//方式一
/*func main() {
	http.HandleFunc("/", Redirect)
	http.HandleFunc("/add", Add)
	http.ListenAndServe(":8080", nil)
}*/

//方式二
/*func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/",Redirect)
	mux.HandleFunc("/add", Add)

	server := &http.Server{
		Addr: ":8080",
		Handler: mux,
	}

	if err := server.ListenAndServe();err != nil {
		log.Fatalln(err)
	}else {
		log.Println("web server go started")
	}
}*/

//方式三
type WelcomeHandle struct {
	WelcomeMessage string
}

func (wel WelcomeHandle) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(w, "%s", wel.WelcomeMessage)
}

//HandlerFunc LogInterceptor  HandlerFunc 的日志 interceptor

func LogHandlerFuncInterceptor(handlerFunc http.HandlerFunc) http.HandlerFunc {
	return func(writer http.ResponseWriter, request *http.Request) {
		log.Printf("请求url :%s", request.URL)
		handlerFunc(writer, request)
	}
}

//Handler LogInterceptor  Handler 日志 interceptor
type LogHandlerInterceptor struct {
	handler http.Handler
}

func (l LogHandlerInterceptor) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	log.Printf("请求url :%s", request.URL)
	l.handler.ServeHTTP(writer, request)
}

/*func main(){
	mux := http.NewServeMux()
	mux.Handle("/welcome",LogHandlerInterceptor{WelcomeHandle{"hello!"}})
	mux.HandleFunc("/", LogHandlerFuncInterceptor(Redirect))
	mux.HandleFunc("/add", LogHandlerFuncInterceptor(Add))

	server := &http.Server{Addr: ":8080", Handler: mux,}

	if err := server.ListenAndServe(); err != nil {
		log.Fatalln(err)
	}else{
		log.Println("started ..")
	}
}*/

//方式四 使用第三方包
/*func main() {
	router := httprouter.New()
	router.GET("/welcome", Index)
	log.Fatal(http.ListenAndServe(":8080", router))
}*/

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	fmt.Fprintf(w, "welcome")
}
